<template>
  <div class="white-bg commonBoxmp">
    <TableV2
      class="flex1"
      :apiFunction="allocatedUserList"
      ref="tableV2Ref"
      :columns="state.columnData"
    >
      <template #tableHeader>
        <div class="jcb aic w100">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
          >
            <el-form-item label="用户名称" prop="userName">
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入用户名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" @click="handleQuery"
                >搜索</el-button
              >
              <el-button size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="handleAddUser">添加用户</el-button>
        </div>
      </template>

      <template #operation>
        <el-table-column label="操作" fixed="right" width="160px" align="left">
          <template #default="scope">
            <el-button type="text" @click="cancelAuthUser(scope.row)"
              >取消授权</el-button
            >
          </template>
        </el-table-column>
      </template>
    </TableV2>

    <selectUser
      ref="selectUserRef"
      @getUsers="handlebindUser"
      :roleId="route.params.roleId"
    ></selectUser>
  </div>
</template>

<script setup lang="tsx">
import {
  ref,
  reactive,
  getCurrentInstance,
  onMounted,
  nextTick,
  unref,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import Column from "/@ts/components/table/Column";
import selectDict from "/@/components/selectDict/index.vue";
import selectUser from "/@/views/system/role/selectUser.vue";
import DictTag from "/@/components/DictTag/index.vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import formatTool from "/@ts/hooks/format";
import {
  allocatedUserList,
  authUserCancel,
  authUserCancelAll,
  authUserSelectAll,
} from "/@ts/axios/urlApi/system/role";
import {
  treeselect as menuTreeselect,
  roleMenuTreeselect,
} from "/@ts/axios/urlApi/system/menu";
const router = useRouter();
const route = useRoute();
const { parseTime, addDateRange, getDict } = formatTool();
/*
基本数据类型
引用数据类型（复杂类型） 个人建议 ref初始化变量 
ref 和 reactive 本质我们可以简单的理解为ref是对reactive的二次包装, 
ref定义的数据访问的时候要多一个.value
*/
const dialogVisible = ref(true);
const tableV2Ref = ref();
const state: any = reactive({
  openDataScope: false,
  defaultProps: {
    children: "children",
    label: "label",
  },
  menuOptions: [],
  deptOptions: [],

  deptExpand: false,
  deptNodeAll: false,
  menuExpand: false,
  menuNodeAll: false,
  // 表格基础配置 start
  title: "",
  form: {},
  userVisible: false,
  rules: {
    roleName: [
      { required: true, message: "角色名称不能为空", trigger: "blur" },
    ],
    roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
    roleSort: [
      { required: true, message: "角色顺序不能为空", trigger: "blur" },
    ],
  },
  dateRange: [], //时间范围筛选

  height: 0,
  tableData: [],
  columnData: [
    {
      label: "用户名称",
      visible: true,
      prop: "userName",
    },
    {
      label: "用户昵称",
      visible: true,
      prop: "nickName",
    },
    {
      label: "邮箱",
      visible: true,
      prop: "email",
    },

    {
      label: "手机",
      prop: "phonenumber",
      visible: true,
    },
    {
      label: "状态",
      visible: true,
      prop: "status",
      render: ({ row }: any) => {
        return (
          <DictTag
            values={row.status}
            dataType="primary"
            options={dict.sys_normal_disable}
          ></DictTag>
        );
      },
    },
    {
      label: "创建时间",
      visible: true,
      prop: "createTime",
    },
  ],
  loading: false,
  // 表格基础配置 end
});
// 表格基础配置 start
const pageInfo = reactive<PageInfoConfig>({
  currentPage: 1,
  total: 10,
  pageSize: 10,
  pageSizes: [10, 20, 30, 40],
  layout: "total, prev, pager, next,sizes",
});
const queryFormInit = {
  pageNum: 1,
  pageSize: 10,
  userName: "",
  phonenumber: "",
};
const queryParams = reactive(JSON.parse(JSON.stringify(queryFormInit)));
const getCurrentColumns = (data: Column[]) => {
  state.columnData = data;
};
const getHeight = (height: number) => {
  state.height = height;
};
const handleSizeChange = (size: number) => {
  pageInfo.pageSize = size;
  getList();
};
const handleCurrentChange = (page: number) => {
  pageInfo.currentPage = page;
  getList();
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  let params = unref(queryParams);
  tableV2Ref.value.getList(params);
};

const resetQuery = () => {
  // 将对象的属性复制为初始值
  Object.assign(queryParams, queryFormInit);
  handleQuery();
};
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate();
  if (state.form.userId != undefined) {
    // updateRole(state.form).then((response: any) => {
    //   ElMessage.success("修改成功");
    //   state.userVisible = false;
    //   getList();
    // });
  } else {
    // addRole(state.form).then((response: any) => {
    //   ElMessage.success("新增成功");
    //   state.userVisible = false;
    //   getList();
    // });
  }
};

/** 修改按钮操作 */
const cancelAuthUser = (row: any) => {
  const roleId = queryParams.roleId;
  ElMessageBox.confirm('确认要取消该用户"' + row.userName + '"角色吗？')
    .then(function () {
      return authUserCancel({ userId: row.userId, roleId: roleId });
    })
    .then(() => {
      ElMessage.success("取消授权成功");
    })
    .catch(function () {});
};
let selectUserRef = ref();
const handleAddUser = () => {
  selectUserRef.value.show();
  // getMenuTreeselect();
  // state.form = {};
  // state.title = "添加角色";
  // state.userVisible = true;
  // nextTick(() => {
  //   console.log("treeRef :>> ", treeRef.value);
  // });
};
// 表格基础配置 end
//查询用户列表
const getList = () => {
  state.loading = true;
  queryParams.pageNum = pageInfo.currentPage;
  queryParams.pageSize = pageInfo.pageSize;
  allocatedUserList(queryParams).then((response: ResponseConfig) => {
    state.tableData = response.rows;
    pageInfo.total = response.total;
    state.loading = false;
  });
};
const ruleFormRef = ref<FormInstance>();

// 角色状态修改
const handleStatusChange = (row?: any) => {
  let text = row.status === "0" ? "启用" : "停用";
  ElMessageBox.confirm('确认要"' + text + '""' + row.roleName + '"角色吗？')
    .then(function () {
      // return changeRoleStatus(row.roleId, row.status);
    })
    .then(() => {
      ElMessage.success(text + "成功");
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
};

// 树权限（父子联动）
const handleCheckedTreeConnect = (value: any, type: any) => {
  if (type == "menu") {
    state.form.menuCheckStrictly = value ? true : false;
  } else if (type == "dept") {
    state.form.deptCheckStrictly = value ? true : false;
  }
};
const handlebindUser = (row: any) => {
  const roleId = queryParams.roleId;
  const userIds = row.ids.join(",");
  if (userIds == "") {
    ElMessage.error("请选择要分配的用户");
    return;
  }
  authUserSelectAll({ roleId: roleId, userIds: userIds }).then(
    (res: ResponseConfig) => {
      ElMessage.success(res.msg);
      if (res.code === 200) {
        selectUserRef.value.hide();
      }
    },
  );
};
let dict: any = reactive({
  sys_normal_disable: [],
});
onMounted(async () => {
  dict.sys_normal_disable = await getDict("sys_normal_disable");
  getList();
});
onMounted(() => {
  const roleId: any = route.params && route.params.roleId;
  if (roleId) {
    queryParams.roleId = roleId;
    let params = unref(queryParams);
    tableV2Ref.value.getList(params);
  }
});
</script>

<style scoped lang="scss"></style>
